package com.ocom.emqx.timer;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.ocom.common.request.emqx.TimerMqttOrderRequest;
import com.ocom.common.utils.CommonUtil;
import com.ocom.emqx.client.PayconfigFeignService;
import com.ocom.emqx.handle.MqttSendClient;
import com.ocom.emqx.util.EmqxApiUtil;
import com.ocom.emqx.vo.MqttTopicVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Slf4j
@Component
public class WashingMachineTask  {

    @Autowired
    MqttSendClient mqttSendClient;

    @Autowired
    PayconfigFeignService payconfigFeignService;

    @Value("${mqttApi}")
    private String mqttAddress;

    @Value("${mqtt.auth}")
    private  String authString;
    //发起定时查询
    @Scheduled(fixedRate = 60000)
    public void scheduled1() {
        long tims = System.currentTimeMillis();

        String objectMap =  EmqxApiUtil.doGet(mqttAddress + "/api/v5/topics",authString);
//        String objectMap =  EmqxApiUtil.doGet( "http://47.112.180.46:18083/api/v5/topics","7e365f775657dc0e:SnH5IfmErbMKNw6dM9Ap2yPmiDuQ3hwrHltG7H2FpmgE");

//        log.info("mqtt 洗衣机在线设备 执行时间1【{}】 ",System.currentTimeMillis()-tims);

        if(CommonUtil.isNull(objectMap))return;

        MqttTopicVo mqttTopicVo = JSON.parseObject(objectMap,MqttTopicVo.class);

        //机器状态变动的机器
        List<String> chageState =new ArrayList<>();

        for (MqttTopicVo.TopicVo topicVo:mqttTopicVo.getData()){
            if(topicVo.getTopic().startsWith("ws/cm/YH")){
                mqttSendClient.publish(false,  topicVo.getTopic() , "0400015301" );
                chageState.add(topicVo.getTopic().replace("ws/cm/",""));
            }
        }

//        log.info("mqtt 洗衣机在线设备 执行时间2【{}】 ",System.currentTimeMillis()-tims);


        payconfigFeignService.updateMqttDeviceOnline(chageState);


        log.info("mqtt 洗衣机在线设备 执行时间3【{}】 返回【{}】",System.currentTimeMillis()-tims,mqttTopicVo);
//        mqttSendClient.publish(false,  "ws/cm/YH2408173796", "0400015301" );

    }

    //定时任务
    @Scheduled(fixedRate = 120000)
    public void scheduled2(){
        List<Integer> statusList = Lists.newArrayList(11,13,31,0);
        String month = DateUtil.format(new Date(),"yyyyMM");
        statusList.forEach(status->{
            TimerMqttOrderRequest timerMqttOrderRequest = new TimerMqttOrderRequest();
            timerMqttOrderRequest.setOrderState(status);
            timerMqttOrderRequest.setMonthValue(month);
            this.payconfigFeignService.timerMqttOrder(timerMqttOrderRequest);
        });
    }

}
